//
//  iseditViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/24.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "OAUnDoneListCell.h"
#import "ckUnDonelistCell.h"
#import "iseditViewController.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OAUnDoneListCell.h"
#import "OADetailModel.h"
#define  KTozbPagdMethod @"tozbPage" //待办 分页列表
#import "detailViewController.h"

@interface iseditViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页



@end

@implementation iseditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:[NSDate date]];
_type = @"liuzhuan";
       self.title = @"已办公文";

    _year = [components year];
    _yearstring = [NSString stringWithFormat:@"%ld",(long)_year];
                  [self _iniview];

//        self.tableView.delegate = self;
//    self.tableView.dataSource =self;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshOADetailData" object:nil];
   
}
- (void)_iniview{

    
   _button1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, (kScreenWidth-30)/2, 30)];
    [_button1 setTitle:@"流转中" forState:UIControlStateNormal];
   [_button1 addTarget:self action:@selector(buttonAction1:) forControlEvents:UIControlEventTouchUpInside];
          [_button1.layer setBorderColor:[UIColor blackColor].CGColor];
    [_button1.layer setBorderWidth:1];
 [_button1.layer setMasksToBounds:YES];
   [_button1 setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
      [_button1 setTitleColor:[UIColor blueColor]forState:UIControlStateSelected];

        _button1.layer.cornerRadius = _button1.height/2;

[_button1 layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight
                        imageTitleSpace:10];

    [self.view addSubview:_button1];

_button2 = [[UIButton alloc] initWithFrame:CGRectMake(_button1.right+10, 5, (kScreenWidth-30)/2, 30)];
       [_button2 setTitle:@"已归档" forState:UIControlStateNormal];


      [_button2.layer setBorderColor:[UIColor blackColor].CGColor];
    [_button2.layer setBorderWidth:1];
 [_button2.layer setMasksToBounds:YES];
   [_button2 setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
         [_button2 setTitleColor:[UIColor blueColor]forState:UIControlStateSelected];

   [_button2 addTarget:self action:@selector(buttonAction2:) forControlEvents:UIControlEventTouchUpInside];
        _button2.layer.cornerRadius = _button2.height/2;

    [self.view addSubview:_button2];
    
 _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, kScreenWidth, kScreenHeight-kTopHeight-30-10) style:UITableViewStylePlain];

         self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//_tableView.bounces = NO;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    
    [self.view addSubview:_tableView];
                     __weak typeof(self) weakSelf = self;

     [self.tableView addHeaderWithCallback:^{
        weakSelf.currentPage = 1;

        [weakSelf loadData]; //加载网络数据
    }];
    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
             [weakSelf loadMore];
        }else{
        
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
    
        }
       
    }];

}
- (void)buttonAction1:(UIButton *)btn{
btn.selected = !btn.selected;
if (btn.selected) {
    _button2.selected = NO;
}
_type = @"liuzhuan";
[self loadData];

}
- (void)buttonAction2:(UIButton *)btn{
btn.selected = !btn.selected;
if (btn.selected) {
    _button1.selected = NO;
}
_type = @"guidang";
[self loadData];

}
#pragma mark 刷新数据
-(void)refreshData{
    
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}

-(NSMutableArray*)dataArray{
    if (_dataArray == nil) {
      _dataArray =   [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark 加载网络数据
-(void)loadData{
self.currentPage = 1;
if ([_type isEqualToString:@"liuzhuan"]) {
     NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [HttpTools requestWithURL:Kexchrecent arrays:array method:KextoybSwPage success:^(id JSON) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
           [self.dataArray removeAllObjects];
        }
//         NSData *jsonData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
//    NSError *err;
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
//                                                        options:NSJSONReadingMutableContainers
//                                                          error:&err];
  _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
        self.totalCounts =[JSON[@"number"] intValue];
        if(JSON[@"number"]){
       self.title = [NSString stringWithFormat:@"已办工作(流转中%@)",JSON[@"number"] ];}
       else{
       self.title = @"已办公文";
       
       }
      _adic= JSON[@"display"];
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}

        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
        [self.view makeToast:@"暂时还没有已办公文哦"];
        }
    } failure:^(NSError *error) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

     [self.tableView headerEndRefreshing];
        
    }];
}else{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"year":_yearstring},@{@"tyoe":@"br"},@{@"sName":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexexcharchiveURL arrays:array method:@"archivePage"success:^(id JSON) {
    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
         self.totalCounts =10000;
  if(JSON[@"number"]){
       self.title = [NSString stringWithFormat:@"已办工作(归档%@)",JSON[@"number"] ];}
       else{
       self.title = @"已办公文";
       
       }
//       self.title = [NSString stringWithFormat:@"公文查询(%@)",JSON[@"number"] ];

         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
    }];
    
}
   
 
}

#pragma mark 加载更多
-(void)loadMore{
if ([_type isEqualToString:@"liuzhuan"])
{ NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:Kexchrecent arrays:array method:KextoybSwPage success:^(id JSON) {
        NSArray *array = JSON[@"data"];
  for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];
        self.currentPage++;
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
       
    } failure:^(NSError *error) {
         [self.tableView footerEndRefreshing];
    }];}
    else{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
//        NSArray * array = @[@{@"userId":userId},@{@"dbpath":[NSString stringWithFormat:@"%ld",_year]},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];

    NSArray * array = @[@{@"year":_yearstring},@{@"tyoe":@"br"},@{@"sName":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexexcharchiveURL arrays:array method:@"archivePage" success:^(id JSON) {
                NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
//_adic= JSON[@"display"];

//       self.title = [NSString stringWithFormat:@"公文查询(%lu)",(unsigned long)[array count]];
    self.currentPage++;
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];
    
}
   
}


//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
    
     self.title = [NSString stringWithFormat:@"已办公文(%lu)",(unsigned long)self.totalCounts];
   
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:15 minsWidth:60];

    return  titleFloat  +75+10;

//return ( KScreenHeight-64)/10;
}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 static NSString *CellIdentifier = @"Cell";
    ckUnDonelistCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {
        cell=[[ckUnDonelistCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
        cell.adic = _adic;

    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;

//    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
//    UnDoneModel * model = self.dataArray[indexPath.row];
//    cell.model = model;
//    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *dic = self.dataArray[indexPath.row];
if ([_type isEqualToString:@"liuzhuan"]) {
        detailViewController * detailVC = (detailViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];
detailVC.type = @"work1";
detailVC.hidesBottomBarWhenPushed = YES;
        detailVC.fileId = dic[@"unid"];

[self.navigationController pushViewController:detailVC animated:YES];
}else{
  detailViewController * detailVC = (detailViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];
detailVC.fileId = dic[@"unid"];
detailVC.type = @"chaxun";
detailVC.year =  _yearstring;

[self.navigationController pushViewController:detailVC animated:YES];

}




}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
